(function (window, $, undefined) {
  'use strict';

  var dictData = {
    type: {
      '1': '常规价',
      '2': '套餐价',
      '3': '一口价'
    },
    status: {
      '101': '启用',
      '102': '禁用'
      // '103': '删除'
    },
    carType: {
      '1': '舒适型',
      '2': '商务七座',
      '3': '豪华轿车'
    },
    serType: {
      '1': '接机',
      '2': '送机',
      '3': '接站',
      '4': '送站',
      '5': '预约车'
    },
    cityId: {

    }
  };

  var priceData;

  var $layerPrice = $('#layer-price');
  var $formPrice = $('#form-price');

  main(function () {

    var $tablePrice = $('#table-price');
    util.jqGrid($tablePrice, {
      url: ajaxURL.PRICE + '/caculationrule/getPriceCaculationRuleListByCondition',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 320,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { name: 'kid', key: true, hidden: true },
        { label: '编号', name: 'kid', width: 30 },
        { label: '报价规则名称', name: 'ruleName', width: 80 },
        {
          label: '报价类型', name: 'type', width: 50, formatter: function (v, o, r) {
            return dictData.type[v] || '';
          }
        },
        {
          label: '城市', name: 'cityId', width: 50, formatter: function (v, o, r) {
            return dictData.cityId[v] || '';
          }
        },
        // { label: '服务类型', name: 'serType', width: 50, formatter: function (v, o, r) {
        //   return dictData.serType[v] || '';
        // } },
        { label: '车辆类型', name: 'carType', width: 60, formatter: function (v, o, r) {
          return dictData.carType[v] || '';
        } },
        { label: '起步价', name: 'startFee', width: 60 },
        { label: '里程费', name: 'unitpricepermile', width: 60 },
        { label: '时长费', name: 'unitpriceperminute', width: 60 },
        { label: '远途费', name: 'farAwayPrice', width: 60 },
        { label: '夜间服务费', name: 'nightPrice', width: 60 },
        { label: '出城费', name: 'outTownPrice', width: 60 },
        { label: '报价状态', name: 'status', width: 60, formatter: function (v, o, r) {
          return dictData.status[v] || '';
        } },
        { label: '运价编码', name: 'kid', width: 60, hidden: true }
      ],
      loadComplete: function (res) {
        priceData = {};
        if (res && res.data && res.data.list) {
          $.each(res.data.list, function (_, item) {
            priceData[item.kid] = item;
          });
        }
      },
      pager: '#pager-price'
    });

    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        dictData.cityId[item.cityId] = item.name;
      });
      searchTable();
      $('#btn-search').click(searchTable);
    });

    // 下拉数据
    util.selectHtml($('[name="type"]'), dictData.type, '', '', '请选择');
    util.selectHtml($('[name="carType"]'), dictData.carType, '', '', '请选择');
    util.selectHtml($('[name="status"]'), dictData.status, '', '', '请选择');
    util.selectHtml($('[name="serType"]'), dictData.serType, '', '', '请选择');

    // 搜索
    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tablePrice, data);
      // console.log(data);
    }

    // 时间选择
    laydate.render({
      elem: '#farevaliddate',
      range: '至',
      type: 'datetime',
      done: function (value) {
        // var temp = value.split('至');
        // $('#farevaliddate').removeClass('error').next().val($.trim(temp[0])).next().val($.trim(temp[1])).next().remove();
      }
    });

    // laydate.render({
    //   elem: '#morningpeaktimedate',
    //   range: '至',
    //   type: 'time',
    //   done: function (value) {
    //     var temp = value.split('至');
    //     $('#morningpeaktimedate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
    //   }
    // });
    // laydate.render({
    //   elem: '#eveningpeaktimedate',
    //   range: '至',
    //   type: 'time',
    //   done: function (value) {
    //     var temp = value.split('至');
    //     $('#eveningpeaktimedate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
    //   }
    // });

    // 新增
    $('#btn-add').click(function () {
      $layerPrice.find('input, select').removeAttr('disabled').val('');
      $layerPrice.find('.d-bottom').show();
      util.resetForm($formPrice);

      $layerPrice.find('[data-operDate]').text(util.getDate(true));
      $layerPrice.find('[data-operMan]').text('');

      util.layerOpen({
        title: '新增报价规则',
        content: $layerPrice,
        area: ['1000px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          savePrice();
        },
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    });

    // 根据 `yyyyMMddhhmmss` 形式的值返回一个 `yyyy-MM-dd hh:mm:ss` 的字符串
    function curFormat(v) {
      var temp = String(v).split('');
      temp.splice(12, 0, ':');
      temp.splice(10, 0, ':');
      temp.splice(8, 0, ' ');
      temp.splice(6, 0, '-');
      temp.splice(4, 0, '-');
      return temp.join('');
    }

    // 查看
    $('#btn-view').click(util.oneCheck($tablePrice, function (id, data) {
      $layerPrice.find('input, select').removeAttr('disabled').val('');
      $layerPrice.find('[name="type"], [name="carType"], [name="cityId"]').attr('disabled', 'disabled');
      // $layerPrice.find('.d-bottom').hide();
      util.resetForm($formPrice);
      var curData = priceData[id];

      // 时间处理
      if (+curData.farevalidon && +curData.farevalidoff) {
        curData.farevaliddate = [curFormat(curData.farevalidon), curFormat(curData.farevalidoff)].join(' 至 ');
      }
      // if (+curData.morningpeaktimeon && +curData.morningpeaktimeoff) {
      //   curData.morningpeaktimedate = [curData.morningpeaktimeon, curData.morningpeaktimeoff].join(' 至 ');
      // }
      // if (+curData.eveningpeaktimeon && +curData.eveningpeaktimeoff) {
      //   curData.eveningpeaktimedate = [curData.eveningpeaktimeon, curData.eveningpeaktimeoff].join(' 至 ');
      // }

      util.resetForm($formPrice);
      util.fillForm($formPrice, curData);

      $layerPrice.find('[data-operDate]').text(util.dateFormat(curData.updateTime || curData.createTime) || '');
      $layerPrice.find('[data-operMan]').text(curData.updateBy || curData.createBy || '');

      util.layerOpen({
        title: '查看/修改',
        content: $layerPrice,
        area: ['1000px', ''],
        btn: ['确认提交', '取消'],
        yes: function (index) {
          savePrice(id);
        }
      });
    }));

    var $validate = $formPrice.validate({
      rules: {
        ruleName: { required: true },
        type: { required: true },
        carType: { required: true },
        cityId: { required: true },
        startFee: { required: true },
        unitpricepermile: { required: true },
        unitpriceperminute: { required: true },
        farAwayPrice: { required: true },
        nightPrice: { required: true },
        outTownPrice: { required: true },
        farevaliddate: { required: true },
        morningpeaktimeon: { required: true, reg: /^\d{4}$/ },
        morningpeaktimeoff: { required: true, reg: /^\d{4}$/ },
        eveningpeaktimeon: { required: true, reg: /^\d{4}$/ },
        eveningpeaktimeoff: { required: true, reg: /^\d{4}$/ },
        nightPriceStartTime: { required: true, digits: true, max: 24, min: 0 },
        nightPriceEndTime: { required: true, digits: true, max: 24, min: 0 }
      },
      messages: {
        ruleName: { required: '请输入规则名称' },
        type: { required: '请选择报价类型' },
        carType: { required: '请选择车辆类型' },
        cityId: { required: '请选择城市' },
        startFee: { required: '请输入起步费' },
        unitpricepermile: { required: '请输入里程费' },
        unitpriceperminute: { required: '请输入时长费' },
        farAwayPrice: { required: '请输入远途费' },
        nightPrice: { required: '请输入夜间服务费' },
        outTownPrice: { required: '请输入出城费' },
        farevaliddate: { required: '请输入运价有效期' },
        morningpeaktimeon: { required: '请输入早高峰开始时间' },
        morningpeaktimeoff: { required: '请输入早高峰结束时间' },
        eveningpeaktimeon: { required: '请输入晚高峰开始时间' },
        eveningpeaktimeoff: { required: '请输入晚高峰结束时间' },
        nightPriceStartTime: { required: '请输入夜间服务费收取开始时间', digits: '请输入整数' },
        nightPriceEndTime: { required: '请输入夜间服务费收取结束时间', digits: '请输入整数' }
      // },
      // errorPlacement: function (error, element) { //错误信息位置设置方法
      //   error.appendTo(element.parents('.form-container')); //这里的element是录入数据的对象
      }
    });

    // 新增保存操作
    function savePrice(kid, index) {
      var data = util.formData($formPrice);

      // util.toTimeStamp(data, [
      //   'farevalidon',
      //   'farevalidoff'
      // ]);

      if (data.farevaliddate) {
        var temp = data.farevaliddate.split('至');
        data.farevalidon = +util.dateFormat($.trim(temp[0]), 'yyyyMMddhhmmss');
        data.farevalidoff = +util.dateFormat($.trim(temp[1]), 'yyyyMMddhhmmss');
      }

      // data.morningpeaktimeon = data.morningpeaktimeon.split(':').slice(0, 2).join('');
      // data.morningpeaktimeoff = data.morningpeaktimeoff.split(':').slice(0, 2).join('');
      // data.eveningpeaktimeon = data.eveningpeaktimeon.split(':').slice(0, 2).join('');
      // data.eveningpeaktimeoff = data.eveningpeaktimeoff.split(':').slice(0, 2).join('');

      // delete data.eveningpeaktimedate
      // delete data.farevaliddate
      // delete data.morningpeaktimedate

      var strMsg = kid ? '确定修改该报价信息？' : '确定新增该报价信息？';
      var postURL = ajaxURL.PRICE + (kid ? '/caculationrule/updatePriceCaculationRule' : '/caculationrule/addPriceCaculationRule');
      var strSuccess = kid ? '修改成功' : '新增成功';

      if (kid) {
        data.kid = kid;
      }

      if (data.nightPriceStartTime === data.nightPriceEndTime) {
        return util.tip.warn('夜间服务费收取的起止时间不能相同！');
      }

      if ($validate.form()) {
        layer.confirm(strMsg, function () {
          util.post(postURL, data, function (res) {
            layer.closeAll();
            util.tip.success(strSuccess);
            $tablePrice.trigger('reloadGrid');
          });
        });
      }
    }

    // 复核
    $('#btn-audit').click(util.oneCheck($tablePrice, function (id, data) {
      util.tip.warn('复核操作...');
    }));

    // 启用
    $('#btn-active').click(util.oneCheck($tablePrice, function (id, data) {
      util.tip.warn('启用操作...');
    }));

    // 禁用
    $('#btn-ban').click(util.oneCheck($tablePrice, function (id, data) {
      util.tip.warn('禁用操作...');
    }));



  });


})(window, jQuery);
